<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Request;
use think\Db;
use fast\Jssdk3;



class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    // protected $noNeedLogin = ['login', 'register', 'third'];
    // protected $noNeedRight = ['*'];
    // protected $layout = '';

    public function  _initialize(){
        $this->_domain = $this->request->domain();
        if(!empty($this->request->get('o'))){
             session('copenid',$this->request->get('o'));
        }
        
        $this->appId = 'wx63c391768f362ca8';  //wxe6747dc052817254
        $this->appSecret = '512ec5eb6117b86bcaccf3f10b45edc2';  //
         if(empty(session('diyici_url'))){
            session('diyici_url',$this->request->action());
        }
      
    }

 



    public function loginout(){
        session(null);
        $this->redirect('/index/index/me');
    }
  

    //查询openid的信息
    private function get_openid_user($openid){
    	$data = Db::name('wxuser')->where('openid',$openid)->find();
    	return $data;
    }

    public function index()
    {  
        //$this->islogin();

 
        // dump($my_data);
        // exit();
        $this->view->assign('site',config('site'));
        return $this->view->fetch();       
    }
     public function about(){
        $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    public function contact(){
        $this->islogin();
        $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    public function membercentre(){
        $this->islogin();

        $this->view->assign('wxuser',$this->get_openid_user(session('user.openid')));
        $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    public function registered(){
        $this->islogin();
        $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

    public function repair(){
        $this->islogin();
        $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }
    
    public function suggestions(){
        $this->islogin();
        $this->view->assign('site',config('site'));
        return $this->view->fetch();  
    }

   



    private function islogin(){
        //验证是否登录过，如果没有登录就跳转
         if(empty(session('user'))){
                $this->getUserOpenId();
            // $this->redirect('/index/index/me');
                exit();
            }else{
                // echo " ";
                // if(!$this->pd_start()){
                //     $this->redirect('/index/index/nostart');
                // }
                // dump(session('openid'));
            }

    }

  

    public function login(){
        $this->getUserOpenId();
    }

    public function getUserOpenId(){

        //2.获取到网页授权的access_token        
        
        
        if(empty($this->request->get('code'))){
            $this->getBaseInfo();
            exit();
        }
        // dump($this->request->get());
        $code = $this->request->get('code');
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code ";
        //3.拉取用户的openid
        $res = file_get_contents($url);

        $data = json_decode($res,true);
        if(!empty($data['access_token']) && !empty($data['openid'])){
            $this->access_token=$data['access_token'];
            $this->refresh_token=$data['refresh_token'];
            
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN"; 
            $userInfo = file_get_contents($url);
            $user_res = json_decode($userInfo,true);
          

                session('user',$user_res);
                $this->add_Wxuser($user_res);


                    if(!empty(session('diyici_url'))){
                        $this->redirect($this->_domain.'/index/index/'.session('diyici_url'));
                    }
                    $this->redirect($this->_domain.'/index/index/index');
  

        }else{
            //错误就打印代码
        	dump($data);
        	// $this->getUserOpenId();
        	exit();
        }
    }

        //获取code
    public function getBaseInfo(){
        //1.获取到code        
        $redirect_uri=urlencode($this->_domain."/index/index/getUserOpenId");
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appId."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=xiaohe#wechat_redirect";
        $this->redirect($url);
    }


    public function add_Wxuser($user){

        $res_user=Db::name('wxuser')->where('openid',$user['openid'])->find();

        $db_data['nickname'] = $user['nickname'];
        $db_data['head_url'] = $user['headimgurl'];
        $db_data['openid'] = $user['openid'];
       
        // $db_data['copenid'] = $user['copenid'];
        $db_data['sex'] = $user['sex'];
        $db_data['updatetime']=time();

        if(!$res_user) {
            //用户不存在，创建用户，没有详细信息
            $db_data['copenid'] =  session('copenid');//看需不需要修改推荐人
            
            $db_data['createtime']=time();
            //再次查询3-2新增 第几个进入
            $max_sort=Db::name('wxuser')->max('sort');
            // dump($manx_sort);
            if(!$max_sort){
                $max_sort = 0;//防止数据库清空默认为1
            }
            $db_data['sort'] = ++$max_sort;

      
            $row = Db::name('wxuser')->insert($db_data);
        }else{ //修改头像地址和昵称以防用户修改

            $row = Db::name('wxuser')->where('openid',$user['openid'])->update($db_data);
            // if($row!=null)
                // echo "更新个人资料成功";
        }   
        
     
    }




    


}
